<!--
 @description 品质主页
 @fileName index.vue
 @author maliang
 @created 2022/02/17 10:01:00
-->
<template>
  <div>
    <div class="top-container">
      <div class="banner">
        <img src="@/assets/image/banner_quality.png">
      </div>
      <div class="main-core-page">
        <span class="icon-tip left" />
        <span class="icon-tip right" />
        <div class="wrapper">
          <div class="main-title">
            <div style="flex:1">核心指标</div>
            <div class="core-time" @click="showCalendar = true">
              <span>{{ coreDateShow }}</span>
              <svg-icon icon-class="xia" />
            </div>
          </div>
          <core-data :core-date="coreDate" />
        </div>
      </div>
    </div>
    <div id="tabFixed" class="tab-titles" :class="{ is_fixed: isFixed }">
      <div class="tab-box" :class="{ 'has-sub': tabName !== 'order' }">
        <template v-for="(item, index) in pageTabs">
          <div
            :key="index"
            class="tab "
            :class="{ active: tabName === item.name }"
            @click="tabName = item.name"
          >
            <span>{{ item.title }}</span>
          </div>
        </template>
      </div>
    </div>
    <div class="main-page">
      <module-item
        class="module-item"
        :module-title="tabName + '各分厂合格率'"
      >
        <histogram
          slot="content"
          :show-legend="false"
          :x-axis-data="yieldColumnarXAxisData"
          :series-data="yieldColumnarSeriesData"
          :series-bar-config="seriesBarConfig"
          @selectedCallback="branchFactorySelectedCallback"
        />
      </module-item>
      <module-item
        class="module-item"
        :module-title="currentSelectedBranchFactoryName + '近30日趋势'"
      >
        <line-chart
          slot="content"
          :show-legend="false"
          :x-axis-data="thirtyDayXAxisData"
          :series-data="thirtyDaySixSeriesData"
          :axis-label-rotate="40"
          :symbol-size="4"
          :grid-data="{ top: 20 }"
          @selectedCallback="thirtyDaySelected"
        />
      </module-item>
      <module-item
        class="module-item"
        :module-title="
          currentSelectedBranchFactoryName + '产线合格率TOP10'
        "
      >
        <div slot="other">
          <div class="type-btn" />
          <span class="date-box">{{ selectedDate }}</span>
        </div>
        <histogram
          slot="content"
          :show-legend="false"
          :x-axis-data="productionLineXAxisData"
          :series-data="productionLineSeriesData"
          :series-bar-config="productionLineSeriesBarConfig"
          @selectedCallback="productionLineSelected"
        />
      </module-item>
      <module-item
        class="module-item"
        :module-title="
          currentSelectedBranchFactoryName +
            selectedProductionLine +
            '问题TOP10'
        "
      >
        <div slot="other">
          <div class="type-btn">
            <span
              v-for="(item, index) in typeOptions"
              :key="index"
              :class="{ active: item.name === currenType }"
              @click="changeTypeHandle(item)"
            >{{ item.name }}</span>
          </div>
          <span class="date-box">{{ selectedDate }}</span>
        </div>
        <problem-histogram
          slot="content"
          :show-legend="false"
          :x-axis-data="problemXAxisData"
          :series-data="problemSeriesData"
          :series-bar-config="seriesBarConfig"
        />
      </module-item>
    </div>
    <van-calendar
      v-model="showCalendar"
      class="custom-calendar"
      color="#12B9A3"
      :row-height="40"
      :min-date="calendarMinDate"
      :max-date="calendarMaxDate"
      @confirm="onConfirmCalendar"
    />
  </div>
</template>
<script>
import CoreDateMixin from '@/mixins/CoreDate'
import CoreData from './components/CoreData'
import ScrollTab from '@/mixins/ScrollTab'
import ModuleItem from '@/views/delivery/components/ModuleItem'
import Histogram from './components/Histogram'
import ProblemHistogram from './components/ProblemHistogram'
import LineChart from './components/LineChart'
import {
  findBranchFactoryQualifiedRate,
  getThirtyDayTrend,
  findProductionLineQualifiedRate,
  findProblem,
  findProblemDetails
} from '@/apis/quality'
export default {
  name: 'Quality',
  components: {
    ModuleItem,
    CoreData,
    Histogram,
    LineChart,
    ProblemHistogram
  },
  mixins: [CoreDateMixin, ScrollTab],
  data() {
    return {
      showCalendar: false,
      tabName: '板式',
      pageTabs: [
        { name: '板式', title: '板式' },
        { name: '实木', title: '实木' },
        { name: '软体', title: '软体' }
      ],
      yieldColumnarXAxisData: null,
      yieldColumnarSeriesData: [
        {
          name: '合格率',
          field: 'qualifiedRate'
        }
      ],
      seriesBarConfig: {
        barWidth: '20px'
      }, // 自定义柱状图配置
      productionLineSeriesBarConfig: {
        barWidth: '14px'
      }, // 自定义柱状图配置
      currentSelectedBranchFactoryName: '',
      thirtyDayXAxisData: null,
      thirtyDaySixSeriesData: [
        { name: '合格率', field: 'qualifiedRate' }
      ],
      productionLineXAxisData: null,
      productionLineSeriesData: [
        {
          name: '合格率',
          field: 'qualifiedRate'
        }
      ],
      typeOptions: [
        {
          name: '问题'
        },
        {
          name: '板件'
        }
      ],
      currenType: '问题',
      problemXAxisData: null,
      problemSeriesData: [
        {
          name: '问题数量',
          field: 'qualifiedQuantity'
        }
      ],
      selectedDate: '',
      selectedProductionLine: ''
    }
  },
  watch: {
    coreDate: {
      handler(val) {
        this.findBranchFactoryQualifiedRate()
      },
      immediate: true
    },
    tabName: {
      handler() {
        this.findBranchFactoryQualifiedRate()
      }
    }
  },
  methods: {
    // 获取各分厂合格率
    findBranchFactoryQualifiedRate() {
      this.yieldColumnarXAxisData = null
      findBranchFactoryQualifiedRate({
        date: this.coreDate,
        factoryTypeName: this.tabName
      }).then((res) => {
        // 产线合格率模拟数据
        // res.data = [
        //     {
        //         qualifiedRate: 78,
        //         factoryName: "板式一分厂",
        //     },
        //     {
        //         qualifiedRate: 60,
        //         factoryName: "板式二分厂",
        //     },
        //     {
        //         qualifiedRate: 88,
        //         factoryName: "板式三分厂",
        //     },
        // ];
        if (res.data) {
          const { xAxisData, seriesData } = this.resetLineChartData(
            res.data,
            this.yieldColumnarSeriesData,
            'factoryName'
          )
          this.yieldColumnarXAxisData = xAxisData
          this.yieldColumnarSeriesData = seriesData
          if (
            this.yieldColumnarXAxisData &&
                        this.yieldColumnarXAxisData.length
          ) {
            this.currentSelectedBranchFactoryName = this.yieldColumnarXAxisData[0]
            this.findNearThirtyDayTrend(
              this.currentSelectedBranchFactoryName
            )
          } else {
            this.thirtyDayXAxisData = []
          }
        }
      })
    },
    // 根据分厂查询近30日趋势图表数据
    findNearThirtyDayTrend(factoryName) {
      this.thirtyDayXAxisData = null
      getThirtyDayTrend({
        date: this.coreDate,
        factoryName: factoryName
      }).then((res) => {
        // 近30日趋势数据模拟
        // res.data = [
        //     {
        //         qualifiedRate: 4,
        //         date: "2021-12-09",
        //     },
        //     {
        //         qualifiedRate: 6,
        //         date: "2021-12-03",
        //     },
        //     {
        //         qualifiedRate: 8,
        //         date: "2021-12-05",
        //     },
        // ];
        if (res.data) {
          const { xAxisData, seriesData } = this.resetLineChartData(
            res.data,
            this.thirtyDaySixSeriesData,
            'date'
          )
          this.thirtyDayXAxisData = xAxisData
          this.thirtyDaySixSeriesData = seriesData
          if (
            this.thirtyDayXAxisData &&
                        this.thirtyDayXAxisData.length
          ) {
            this.selectedDate = this.thirtyDayXAxisData[
              this.thirtyDayXAxisData.length - 1
            ]
            this.findProductionLineQualifiedRate(
              factoryName,
              this.selectedDate
            )
            this.findProblemChartsData(
              this.currentSelectedBranchFactoryName,
              this.selectedDate,
              this.selectedProductionLine
            )
          } else {
            this.productionLineXAxisData = []
          }
        }
      })
    },
    // 根据分厂查询产线合格率
    findProductionLineQualifiedRate(factoryName, date) {
      this.productionLineXAxisData = null
      this.problemXAxisData = null
      findProductionLineQualifiedRate({
        date,
        factoryName
      }).then((res) => {
        // 产线合格率数据模拟
        // res.data = [
        //     {
        //         qualifiedRate: 78,
        //         processName: "产线1",
        //     },
        //     {
        //         qualifiedRate: 60,
        //         processName: "产线2",
        //     },
        //     {
        //         qualifiedRate: 88,
        //         processName: "产线3",
        //     },
        // ];
        if (res.data) {
          if (res.data.length > 10) {
            res.data = res.data.splice(1, 10)
          }
          const { xAxisData, seriesData } = this.resetLineChartData(
            res.data,
            this.productionLineSeriesData,
            'processName'
          )
          this.productionLineXAxisData = xAxisData
          this.productionLineSeriesData = seriesData
          if (
            this.productionLineXAxisData &&
                        this.productionLineXAxisData.length
          ) {
            // this.selectedProductionLine = this.productionLineXAxisData[0];
            // this.findProblemChartsData(
            //     factoryName,
            //     date,
            //     this.productionLineXAxisData[0]
            // );
          } else {
            this.problemXAxisData = []
            this.problemSeriesData = [
              {
                name: '问题数量',
                field: 'qualifiedQuantity'
              }
            ]
          }
        }
      })
    },
    // 根据分厂查询问题数据
    async findProblemChartsData(factoryName, date, process) {
      this.problemXAxisData = null
      this.problemSeriesData = [
        {
          name: '问题数量',
          field: 'qualifiedQuantity'
        }
      ]
      const params = {
        date,
        factoryName,
        process
      }
      const findHandel =
                this.currenType === '问题'
                  ? findProblemDetails(params)
                  : findProblem(params)
      const [res] = await Promise.all([findHandel])
      // 产线合格率数据模拟
      // res.data = [
      //     {
      //         qualifiedQuantity: 78,
      //         problemName: "流油，油挂",
      //     },
      //     {
      //         qualifiedQuantity: 60,
      //         problemName: "针孔损坏",
      //     },
      //     {
      //         qualifiedQuantity: 88,
      //         problemName: "油渣",
      //     },
      // ];
      if (res.data) {
        const { xAxisData, seriesData } = this.resetLineChartData(
          res.data,
          this.problemSeriesData,
          'problemName'
        )
        this.problemXAxisData = xAxisData
        this.problemSeriesData = seriesData
      }
    },
    // 各分厂合格率柱状图点击
    branchFactorySelectedCallback(index) {
      this.selectedProductionLine = ''
      this.currentSelectedBranchFactoryName = this.yieldColumnarXAxisData[
        index
      ]
      this.findNearThirtyDayTrend(this.currentSelectedBranchFactoryName)
    },
    // 30日时间选择
    thirtyDaySelected(index) {
      this.selectedDate = this.thirtyDayXAxisData[index]
      this.findProductionLineQualifiedRate(
        this.currentSelectedBranchFactoryName,
        this.selectedDate
      )
      this.findProblemChartsData(
        this.currentSelectedBranchFactoryName,
        this.selectedDate,
        this.selectedProductionLine
      )
    },
    // 产线选择
    productionLineSelected(index) {
      this.selectedProductionLine = this.productionLineXAxisData[index]
      this.findProblemChartsData(
        this.currentSelectedBranchFactoryName,
        this.selectedDate,
        this.selectedProductionLine
      )
    },
    // 问题分类选择
    changeTypeHandle(item) {
      this.currenType = item.name
      this.findProblemChartsData(
        this.currentSelectedBranchFactoryName,
        this.selectedDate,
        this.selectedProductionLine
      )
    },
    // 图数据处理(list: 未处理前的图表数据；seriesData：图列名称与对应字段；xAxisField：x轴对应字段  )
    resetLineChartData(list, seriesData, xAxisField, unit = '') {
      seriesData.forEach((item) => {
        item.data = []
      })
      let copyLsit = JSON.parse(JSON.stringify(list))
      const copySeriesData = JSON.parse(JSON.stringify(seriesData))
      const xAxisData = []
      if (xAxisField === 'date') {
        // 根据日期排序
        copyLsit = copyLsit.sort((a, b) => {
          return (
            Number(a.date.replace(/-/g, '')) -
                        Number(b.date.replace(/-/g, ''))
          )
        })
      }
      copyLsit.forEach((item) => {
        xAxisData.push(item[xAxisField] + unit)
        copySeriesData.forEach((row) => {
          row.data.push(item[row.field])
        })
      })
      return {
        xAxisData,
        seriesData: copySeriesData
      }
    }
  }
}
</script>
<style lang="less" scoped>
// 解决部分机型第一次打开日历选择弹框后出现空白的问题
/deep/.van-calendar__popup.van-popup--bottom,
.van-calendar__popup.van-popup--top {
    height: 79.9%;
}
.banner {
    margin-top: -3px;
}
.tab-box {
    border-radius: 6px !important;
}
.module-item {
    margin-top: 10px;
    position: relative;
    .this-year-num {
        position: absolute;
        right: 10px;
        top: 18px;
        z-index: 2;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 16px;
        letter-spacing: 1px;
        > i {
            font-style: normal;
            color: #e8684a;
            letter-spacing: 0;
        }
    }
    .type-btn {
        display: flex;
        span {
            width: 44px;
            height: 24px;
            border: 1px solid #eeeeee;
            background-color: #eeeeee;
            text-align: center;
            line-height: 22px;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.4);
            &:nth-child(1) {
                border-radius: 4px 0 0 4px;
            }
            &:nth-child(2) {
                border-radius: 0 4px 4px 0;
            }
        }
        .active {
            background: #12b9a3;
            box-shadow: 0px 2px 4px 0px rgba(18, 185, 163, 0.3);
            color: #fff;
            border: 1px solid #12b9a3;
        }
    }
    .date-box {
        position: absolute;
        right: 10px;
        top: 18px;
        z-index: 2;
        font-size: 12px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 16px;
        letter-spacing: 1px;
    }
}
</style>
